﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Genuilder.Extensions.XamlVerifier
{
	public class CorrectionCollection
	{
		internal class Correction
		{
			private string content;
			string _File;
			public Correction(string file)
			{
				content = File.ReadAllText(file);
				Builder = new StringBuilder();
				_File = file;
			}
			public StringBuilder Builder
			{
				get;
				private set;
			}


			int currentIndex = 0;
			public void FlushUntil(int index)
			{
				int length = index - currentIndex;
				if(length == 0)
					return;
				Builder.Append(content.Substring(currentIndex, length));
				currentIndex += length;
			}

			public void Skip(int cNbr)
			{
				currentIndex += cNbr;
			}

			internal void FlushUntilEnd()
			{
				FlushUntil(content.Length);
			}

			internal void ApplyCorrection()
			{
				FlushUntilEnd();
				File.WriteAllText(_File, Builder.ToString());
			}
		}
		internal Dictionary<string, Correction> _Corrections = new Dictionary<string, Correction>();
		internal Correction GetCorrection(string file)
		{
			Correction correction = null;
			if(!_Corrections.TryGetValue(file, out correction))
			{
				correction = new Correction(file);
				_Corrections.Add(file, correction);
			}
			return correction;
		}

		public String this[string index]
		{
			get
			{
				Correction value;
				if(!_Corrections.TryGetValue(index, out value))
					return null;
				return value.Builder.ToString();
			}
		}
	}
	public class XamlCorrector
	{
		public XamlCorrector()
		{

		}
		public IEnumerable<XamlVerifierError> AllErrors()
		{
			foreach(var error in Evaluator.AllErrors())
			{
				var correction = _Corrections.GetCorrection(error.File);
				correction.FlushUntil(error.Index);
				correction.Builder.Append(error.Suggestion);
				correction.Skip(error.CurrentValue.Length);
				yield return error;
			}
			FlushCorrections();
		}

		public void SaveCorrections()
		{
			foreach(var correction in _Corrections._Corrections.Values)
			{
				correction.ApplyCorrection();
			}
		}

		private void FlushCorrections()
		{
			foreach(var correction in _Corrections._Corrections.Values)
			{
				correction.FlushUntilEnd();
			}
		}



		public XamlVerifierEvaluator Evaluator
		{
			get;
			set;
		}

		private readonly CorrectionCollection _Corrections = new CorrectionCollection();
		public CorrectionCollection Corrections
		{
			get
			{
				return _Corrections;
			}
		}
	}
}
